package com.hlingsoft.cms.action.manage;

import com.google.gson.Gson;
import com.hlingsoft.cms.dao.*;
import com.hlingsoft.cms.entity.*;
import com.hlingsoft.cms.entity.Image;
import com.hlingsoft.cms.entity.vo.JsonVo;
import com.hlingsoft.cms.entity.vo.PageVo;
import com.hlingsoft.cms.util.Common;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;


/**
 * Created by selbylei on 2015/5/7.
 */

@Controller
@RequestMapping("/manage/goods")
public class ManageGoodsAction extends ManageBaseAction {

    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private TypeDao typeDao;

    @Autowired
    private ImageDao imageDao;

    @Autowired
    private BrandDao brandDao;

    @Autowired
    private SizeWithPriceDao sizeWithPriceDao;



    /**
     * 商品列表
     *
     * @param pageNum
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/list.htm", method = RequestMethod.GET)
    public String index(
            @RequestParam(value = "p", defaultValue = "1") int pageNum,
            ModelMap modelMap) {
        PageVo<Goods> pageVo = new PageVo<Goods>(pageNum);
        pageVo.setRows(10);
        pageVo.basePath = "/manage/goods/list.htm";
        List<Goods> goodsList = goodsDao.getGoodsList();
        for (Goods goods:goodsList){
            goods.setImage(imageDao.getImageByGoodsId(goods.getId(),0).get(0).getPath());
        }
        pageVo.setList(goodsList);
        pageVo.setCount(goodsList.size());
        modelMap.put("p", pageNum);
        modelMap.put("pageVo", pageVo);

        return "manage/goods/list";
    }


    /**
     * 添加界面
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/add.htm", method = RequestMethod.GET)
    public String add(
            ModelMap modelMap) {
        List<Type> typeList = typeDao.getTypeList();
        List<Brand> brandList = brandDao.getBrandList();

        modelMap.put("typeList", typeList);
        modelMap.put("brandList",brandList);
        return "manage/goods/add";
    }


    /**
     * 添加接口
     *
     * @param file
     * @param name
     * @param price
     * @param typeId
     * @param material
     * @param manufacturer
     * @param mark
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/add.json", method = RequestMethod.POST)
    public JsonVo<String> add(
            @RequestParam(value = "file", required = false) MultipartFile file,
            @RequestParam(value = "file1", required = false) MultipartFile file1,
            @RequestParam(value = "file2", required = false) MultipartFile file2,
            @RequestParam(value = "file3", required = false) MultipartFile file3,
            @RequestParam(value = "name") String name,
            @RequestParam(value = "price") Double price,
            @RequestParam(value = "typeId") int typeId,
            @RequestParam(value = "brandId") Integer brandId,
            @RequestParam(value = "material") String material,
            @RequestParam(value = "manufacturer") String manufacturer,
            @RequestParam(value = "mark") String mark,
            @RequestParam(value = "categoryId") int categoryId,
            @RequestParam(value = "shippingPrice",required = false) Integer shippingPrice
          ) {
        JsonVo<String> json = new JsonVo<String>();
        try {

            Goods goods = new Goods();
            Date now = new Date();
            goods.setName(name);
            goods.setPrice(price);
            goods.setTypeId(typeId);
            goods.setMaterial(material);
            goods.setMark(mark);
            goods.setManufacturer(manufacturer);
            goods.setCreateTime(now);
            goods.setUpdateTime(now);
            if (brandId!=null){
                goods.setBrandId(brandId);
            }
            if (shippingPrice!=null){
                goods.setShippingPrice(shippingPrice.doubleValue());
            }
            goods.setCategoryId(categoryId);
            goodsDao.addGoods(goods);

            //图片上传
            if (file != null) {
                String fileName = file.getOriginalFilename();
                SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                String dateString = simpleFormat.format(new Date());
                Common.putObject(dateString, fileName, file.getInputStream(),
                        file.getSize());
                String imagePath = "http://icake.oss-cn-hangzhou.aliyuncs.com/news/" + dateString + "/" + fileName;
                Image image = new Image();
                image.setPath(imagePath);
                image.setType(0);
                image.setCreateTime(now);
                image.setUpdateTime(now);
                image.setTokeTime(now);
                image.setGoodsId(goods.getId());
                imageDao.addImages(image);
            }

            if (file1 != null) {
                String fileName = file1.getOriginalFilename();
                SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                String dateString = simpleFormat.format(new Date());
                Common.putObject(dateString, fileName, file1.getInputStream(),
                        file1.getSize());
                String imagePath = "http://icake.oss-cn-hangzhou.aliyuncs.com/news/" + dateString + "/" + fileName;
                Image image = new Image();
                image.setPath(imagePath);
                image.setType(1);
                image.setCreateTime(now);
                image.setUpdateTime(now);
                image.setTokeTime(now);
                image.setGoodsId(goods.getId());
                imageDao.addImages(image);
            }
            if (file2 != null) {
                String fileName = file2.getOriginalFilename();
                SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                String dateString = simpleFormat.format(new Date());
                Common.putObject(dateString, fileName, file2.getInputStream(),
                        file2.getSize());
                String imagePath = "http://icake.oss-cn-hangzhou.aliyuncs.com/news/" + dateString + "/" + fileName;
                Image image = new Image();
                image.setPath(imagePath);
                image.setType(1);
                image.setCreateTime(now);
                image.setUpdateTime(now);
                image.setTokeTime(now);
                image.setGoodsId(goods.getId());
                imageDao.addImages(image);
            }
            if (file3 != null) {
                String fileName = file3.getOriginalFilename();
                SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                String dateString = simpleFormat.format(new Date());
                Common.putObject(dateString, fileName, file3.getInputStream(),
                        file3.getSize());
                String imagePath = "http://icake.oss-cn-hangzhou.aliyuncs.com/news/" + dateString + "/" + fileName;
                Image image = new Image();
                image.setPath(imagePath);
                image.setType(1);
                image.setCreateTime(now);
                image.setUpdateTime(now);
                image.setTokeTime(now);
                image.setGoodsId(goods.getId());
                imageDao.addImages(image);
            }
            json.setResult(true);
            return json;
        } catch (IOException e) {
            e.printStackTrace();
            json.setResult(false);
            return json;
        }
    }



    /**
     * 编辑界面
     * @param goodsId
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/update.htm", method = RequestMethod.GET)
    public String edit(
            @RequestParam(value = "goodsId") long goodsId,
            ModelMap modelMap) {
        typeDao.getTypeList();
        List<Image> imageList =imageDao.getImageByGoodsId(goodsId,0);
        List<Image> imageList1 = imageDao.getImageByGoodsId(goodsId,1);
        String image = imageList.get(0).getPath();
        modelMap.put("goods",goodsDao.getGoodsById(goodsId));
        modelMap.put("typeList", typeDao.getTypeList());
        modelMap.put("image",image);
        modelMap.put("imageList1",imageList1);
        return "manage/goods/update";
    }


    /**
     * 编辑提交接口
     * @param goodsId
     * @param file
     * @param name
     * @param price
     * @param typeId
     * @param material
     * @param manufacturer
     * @param mark
     * @param request
     * @param modelMap
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/update.json", method = RequestMethod.POST)
    public JsonVo<String> update(
            @RequestParam(value = "goodsId") long goodsId,
            @RequestParam(value = "file", required = false) MultipartFile file,
            @RequestParam(value = "file1",required = false) MultipartFile file1[],
            @RequestParam(value = "name",required = false) String name,
            @RequestParam(value = "price",required = false) Integer price,
            @RequestParam(value = "typeId",required = false) Integer typeId,
            @RequestParam(value = "material",required = false) String material,
            @RequestParam(value = "manufacturer",required = false) String manufacturer,
            @RequestParam(value = "mark",required = false) String mark,
            @RequestParam(value = "shippingPrice",required = false) Integer shippingPrice,

            HttpServletRequest request, ModelMap modelMap) {
        JsonVo<String> json = new JsonVo<String>();
        try {
            Date now = new Date();
            Goods goods = goodsDao.getGoodsById(goodsId);
            if (name!=null){
                goods.setName(name);
            }
            if (price!=null){
                goods.setPrice(price.doubleValue());
            }
            if (typeId!=null){
                goods.setTypeId(typeId.intValue());
            }
            if (material!=null){
                goods.setMaterial(material);
            }           if(manufacturer!=null){
                goods.setManufacturer(manufacturer);
            }        if (mark!=null){
                goods.setMark(mark);
            }
            if (shippingPrice!=null){
                goods.setShippingPrice(shippingPrice.doubleValue());
            }

            if (file!=null) {

                List<Image> imageList =imageDao.getImageByGoodsId(goodsId,0);
                Image image = imageList.get(0);

                String fileName = file.getOriginalFilename();
                SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                String dateString = simpleFormat.format(new Date());
                Common.putObject(dateString, fileName, file.getInputStream(),
                        file.getSize());
                String imagePath = "http://icake.oss-cn-hangzhou.aliyuncs.com/news/" + dateString + "/" + fileName;


                CommonsMultipartFile cf= (CommonsMultipartFile)file;
                DiskFileItem fi = (DiskFileItem)cf.getFileItem();
                File f = fi.getStoreLocation();
                BufferedImage sourceImg = ImageIO.read(new FileInputStream(f));


                image.setWidth(sourceImg.getWidth());
                image.setHeight(sourceImg.getHeight());
                image.setPath(imagePath);
                image.setUpdateTime(now);

                imageDao.updateImage(image);
            }



            if (file1.length!=0) {
                for (int i = 0; i <file1.length ; i++) {
                    List<Image> imageList =imageDao.getImageByGoodsId(goodsId,1);
                    Image image = imageList.get(i);

                    String fileName = file1[i].getOriginalFilename();
                    SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                    String dateString = simpleFormat.format(new Date());
                    Common.putObject(dateString, fileName, file1[i].getInputStream(),
                            file1[i].getSize());
                    String imagePath = "http://icake.oss-cn-hangzhou.aliyuncs.com/news/" + dateString + "/" + fileName;


                    CommonsMultipartFile cf= (CommonsMultipartFile)file1[i];
                    DiskFileItem fi = (DiskFileItem)cf.getFileItem();
                    File f = fi.getStoreLocation();
                    BufferedImage sourceImg = ImageIO.read(new FileInputStream(f));


                    image.setWidth(sourceImg.getWidth());
                    image.setHeight(sourceImg.getHeight());
                    image.setPath(imagePath);
                    image.setUpdateTime(now);

                    imageDao.updateImage(image);
                }

            }

            goodsDao.updateGoods(goods);
            json.setResult(true);
            return json;
        } catch (IOException e) {
            e.printStackTrace();
            json.setResult(false);
            return json;
        }
    }




    /**
     * 删除商品
     *
     * @param goodsId
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/delete.json")
    @ResponseBody
    public JsonVo<String> delete(@RequestParam(value = "goodsId") long goodsId,
                                 ModelMap modelMap) {
        JsonVo<String> json = new JsonVo<String>();
        goodsDao.deleteGoodsById(goodsId);
        json.setResult(true);
        return json;
    }


    /**
     * 搜索
     * @param name
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/search.json")
    @ResponseBody
    public JsonVo<String> search(@RequestParam(value = "name") String name,
                                 ModelMap modelMap) {

        name = Common.encodeStr(name);

        JsonVo<String> json = new JsonVo<String>();
        String regEx = "[\u4e00-\u9fa5]";
        Pattern pat = Pattern.compile(regEx);
        if (isContainsChinese(pat, name)) {
            List<Goods> goodsList = goodsDao.getGoodsWhenSearch(name);
            Gson gson = new Gson();
            json.setT(gson.toJson(goodsList));
            json.setResult(true);
        } else {
            json.setResult(false);
        }
        return json;
    }




    public static boolean isContainsChinese(Pattern pat, String str) {
        Matcher matcher = pat.matcher(str);
        boolean flg = false;
        if (matcher.find()) {
            flg = true;
        }
        return flg;

    }

}
